import React, { useEffect, useState } from 'react';
import '../../styles/Staffmanage.scss'
import type { ColumnsType } from 'antd/es/table'
import { Table, Button, Modal, TablePaginationConfig, Form, notification, Select } from 'antd'
import { Input } from 'antd';
import { staff_search, staff_add, role_list, staff_del, staff_edit } from '../../utils/api'
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';

const { Search } = Input;

interface Props {

}

//定义每一行的数据对象类型
interface DataType {
    user: string;
    nickname: string;
    name: string;
    phone: string;
    role: string;
    key: string;
}


function Staffmanage(props: Props) {
    // 获取员工列表
    var [stafflist, setStafflist] = useState([])

    // 获取本行的id修改内容
    var [newid, setNewid] = useState('')

    var [form] = Form.useForm();


    // 获取列表数据
    useEffect(() => {
        staff_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
            setStafflist(res.data.list)
            setPagination({ current: 1, pageSize: 10, total: res.data.total })//保存总数
        })
        // 请求角色列表
        role_list().then((res) => {
            console.log(res.data);

            // 处理服务器返回的角色列表
            var arr = res.data.list.map((item: any) => {
                return { label: item.name, value: item._id }
            })
            // console.log(arr);
            setOptions(arr);
        })
    }, [])

    //决定了每一列渲染什么数据
    const columns: ColumnsType<DataType> = [
        {
            title: '账号', //表格列的名字(显示在表格头上)
            dataIndex: 'user', //数据对应的属性名
            //key: 'name' //key是必须的,每一列不同.
        },
        {
            title: '昵称',
            dataIndex: 'nickname',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '手机号',
            dataIndex: 'phone'
        },
        {
            title: '类型',
            dataIndex: ['role', 'name'],
            key: 'role'
        },
        {
            title: '角色',
            dataIndex: ['role', 'name'],
            key: 'role'
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <>
                    <button onClick={() => { edit(record) }} className='iconfont icon-edit'>编辑</button>

                    <button onClick={() => { delt(record) }} className='iconfont icon-delete' style={{ marginLeft: 20 }}>删除</button>
                </>
            ),
        },
    ];

    // 点击删除
    const delt = (item: any) => {

        var it = {
            id: item._id,
            searchKey: '',
            page: pagination.current,
            count: pagination.pageSize
        }
        staff_del(it).then((res) => {
            if (res.data.code == 200) {
                notification.success({ message: '删除成功！' });
                staff_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                    setStafflist(res.data.list)
                    setLoading(false);
                })
            }
        })

    }

    //决定了每一行渲染什么数据
    const data: DataType[] = stafflist;

    //搜索
    const onSearch = (value: string) => {
        staff_search({ searchKey: value, page: pagination.current, count: pagination.pageSize }).then((res) => {
            setStafflist(res.data.list)
        })
    };

    //分页器
    var [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 })
    var [loading, setLoading] = useState(false);

    //分页
    const handleChange = (pagination: TablePaginationConfig) => {
        // // 发请求，获取最新页码对应的数据
        setPagination(pagination)//更新页码
        setLoading(true)
        //pagination 参数 包含有当前最新页码
        //在这里发请求, 获取最新页码对应的数据
        staff_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
            setLoading(false);
            setStafflist(res.data.list)
        });

    }

    // 新增
    // 控制新增表单的显示或隐藏
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 角色列表
    var [options, setOptions] = useState([])
    // 新增表单显示
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 新增表单验证通过，执行
    const onFinish = (values: any) => {
        staff_add(values).then((res) => {
            if (res.data.code == 200) {
                notification.success({ message: '添加成功！' });
                staff_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                    setStafflist(res.data.list)
                    setPagination({ current: 1, pageSize: 10, total: res.data.total })//保存总数
                    setIsModalOpen(false);
                })
            } else if (res.data.code == 400) {
                notification.success({ message: '该用户已存在！' });
            }

        })
    }

    // 编辑的时候
    const [isModalOpenedit, setIsModalOpenedit] = useState(false);

    const showModaledit = () => {
        setIsModalOpenedit(true);
    };
    const handleOkedit = () => {
        setIsModalOpenedit(false);
    };

    const handleCanceledit = () => {
        setIsModalOpenedit(false);
    };

    // 点击编辑
    const edit = (record: any) => {
        showModaledit();
        form.setFieldsValue(record)
        form.setFieldsValue({
            role: record.role._id
        })
        setNewid(record._id)

    }

    // 编辑表单提交
    const onFinishedit = (values: any) => {

        var it = { _id: newid, user: values.user, pass: 'kf1234', nickname: values.nickname, name: values.name, phone: values.phone, role: values.role }

        staff_edit(it).then((res) => {
            if (res.data.code == 200) {
                notification.success({ message: '修改成功！' });
                staff_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                    setStafflist(res.data.list)
                    setIsModalOpenedit(true);
                })

            } else if (res.data.code == 400) {
                notification.success({ message: '该用户已存在！' });
            }
        })
    }


    return (
        <div className='staffmanage'>
            <p>员工管理</p>
            <div className="opet">
                <Search style={{ width: 300, marginRight: 20 }} placeholder="输入员工姓名" onSearch={onSearch} enterButton />
                <Button type="primary" onClick={showModal}>
                    新增客服
                </Button>
                <Modal title="新增客服" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <Form
                        name="basic"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="账号"
                            name="user"
                            rules={[{ required: true, message: '输入账号', }]}
                        >
                            <Input placeholder='输入账号' />
                        </Form.Item>

                        <Form.Item
                            label="昵称"
                            name="nickname"
                            rules={[{ required: true, message: '输入昵称' }]}
                        >
                            <Input placeholder='输入昵称' />
                        </Form.Item>

                        <Form.Item
                            label="姓名"
                            name="name"
                            rules={[{ required: true, message: '输入姓名' }]}
                        >
                            <Input placeholder='输入姓名' />
                        </Form.Item>

                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '输入手机号', }]}
                        >
                            <Input placeholder='输入手机号' />
                        </Form.Item>

                        <Form.Item
                            label="角色"
                            name="role"
                            rules={[{ required: true, message: '选择角色' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={options}
                            />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                添加
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title="编辑客服" open={isModalOpenedit} onOk={handleOkedit} onCancel={handleCanceledit}>
                    <Form
                        name="basic"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinishedit}
                        form={form}
                    >
                        <Form.Item
                            label="账号"
                            name="user"
                            rules={[{ required: true, message: '输入账号' }]}
                        >
                            <Input placeholder='输入账号' />
                        </Form.Item>

                        <Form.Item
                            label="昵称"
                            name="nickname"
                            rules={[{ required: true, message: '输入昵称' }]}
                        >
                            <Input placeholder='输入昵称' />
                        </Form.Item>

                        <Form.Item
                            label="姓名"
                            name="name"
                            rules={[{ required: true, message: '输入姓名' }]}
                        >
                            <Input placeholder='输入姓名' />
                        </Form.Item>

                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '输入手机号', }]}
                        >
                            <Input placeholder='输入手机号' />
                        </Form.Item>

                        <Form.Item
                            label="角色"
                            name="role"
                            rules={[{ required: true, message: '选择角色' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={options}
                            />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                修改
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
            {/* 表格组件 */}
            {/* columns 表格每一列如何渲染 */}
            {/* dataSource 表格的数据源 */}
            <Table columns={columns} dataSource={data} size={'middle'} pagination={pagination} onChange={handleChange} />

        </div>
    );
}

export default Staffmanage;